package com.sharedprint.system.order.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.config.AlipayConfig;
import com.sharedprint.system.goods.pojo.GoodsInfo;
import com.sharedprint.system.goods.service.GoodsInfoService;
import com.sharedprint.system.order.pojo.OrderGoods;
import com.sharedprint.system.order.service.OrderGoodsService;
import com.sharedprint.system.order.service.OrderGoodsServiceImpl;
import com.sun.javafx.image.IntToBytePixelConverter;
import com.alipay.*;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
@Controller
@RequestMapping("/api/orderGoods")
public class OrderGoodsController {
	@Autowired
	OrderGoodsService orderGoodsService;
	
	@Autowired
	GoodsInfoService goodsInfoService;
	
	// 生成随机数
	public static String getRandomNum() {
		Random r = new Random();
		String string = String.valueOf(r.nextInt(900000) + 100000);
		return string;// (int)(Math.random()*999999)
	}

	// 获取当前时间
	public static Date getNowTime() throws ParseException {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String date = dateFormat.format(now);
		return dateFormat.parse(date);
	}	
	
	// 支付宝接口
		@RequestMapping("/alipay.action")
		private void aliyPay(HttpServletRequest request, HttpServletResponse resp) throws AlipayApiException, IOException {
			System.err.println(646546546);
			// ↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
			// 获得初始化的AlipayClient
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
					AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
					AlipayConfig.sign_type);
			// 设置请求参数
			AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
			alipayRequest.setReturnUrl(AlipayConfig.return_url);
			alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
			// 商户订单号，商户网站订单系统中唯一订单号，必填
			String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 付款金额，必填
			String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"), "UTF-8");
			// 订单名称，必填
			String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"), "UTF-8");
			// 商品描述，可空
			String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"), "UTF-8");

			alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
					+ "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

			// 若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
			// alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
			// + "\"total_amount\":\""+ total_amount +"\","
			// + "\"subject\":\""+ subject +"\","
			// + "\"body\":\""+ body +"\","
			// + "\"timeout_express\":\"10m\","
			// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
			// 请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

			// 请求
			String result = alipayClient.pageExecute(alipayRequest).getBody();

			// 输出
			resp.setContentType("text/html;charset=utf-8");
			resp.getWriter().append(result);
		}
	
	@RequestMapping("/queryPageList")
	@ResponseBody
	private Map<String, Object> quertyOrderGoodsList(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		String orderGoodsIds = request.getParameter("orderGoodsIds");
		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (userId !=null) {
			searchMap.put("userId", userId);
			List<Map<String, Object>> cartGoodsList = new ArrayList<Map<String,Object>>();
			if (orderGoodsIds !=null) {
				String[] orderGoodsId = orderGoodsIds.split(",");
				for (String oGId : orderGoodsId) {
					searchMap.put("orderGoodsId", oGId);
					cartGoodsList.add(orderGoodsService.findOrderGoodsList(searchMap).get(0));
				}
			}else {
				cartGoodsList = orderGoodsService.findOrderGoodsList(searchMap);
			}			
			if (cartGoodsList !=null) {
				resultMap.put("success", "1");
				resultMap.put("cartGoodsList", cartGoodsList);
			}else {
				resultMap.put("success", "0");
			}
		}else {
			resultMap.put("success", "0");
		}
		return resultMap;
	}
	/**
	 * 购物车修改商品数量
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateNumber")
	@ResponseBody
	private Map<String, Object> updateNumber(HttpServletRequest request) {
		String orderGoodsId = request.getParameter("orderGoodsId");
		String goodsNumber = request.getParameter("goodsNumber");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int success = 0;
		if (orderGoodsId != null) {
			OrderGoods orderGoods = new OrderGoods();
			orderGoods.setOrdergoodsId(Integer.parseInt(orderGoodsId));
			orderGoods.setGoodsCount(Integer.parseInt(goodsNumber));
			success = orderGoodsService.updateNumber(orderGoods);
			if (success > 0) {
				resultMap.put("success", "1");
			}else {
				resultMap.put("success", "0");
			}
		}else {
			resultMap.put("success", "0");
		}
		return resultMap;
	}
	
	@RequestMapping("/addCart")
	@ResponseBody
	private Map<String, Object> addCart(HttpServletRequest request) throws ParseException{
		String goodsId = request.getParameter("goodsId");
		String userId = request.getParameter("userId");
		int goodsNumber = Integer.parseInt(request.getParameter("number"));
		OrderGoods orderGoods = null;
		int success = 0;
		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		searchMap.put("userId", userId);
		if (userId != null & goodsId !=null) {			
			Map<String, Object> orderGoodsMap = null;
			List<Map<String, Object>> orderGoodsList = orderGoodsService.findOrderGoodsList(searchMap);
			for (Map<String, Object> map : orderGoodsList) {
				if (map.get("Goods_ID").toString().equals(goodsId)) {
					orderGoodsMap = map;
				}
			}
			if (orderGoodsMap !=null) {
				orderGoods = new OrderGoods();
				int price = Integer.parseInt(orderGoodsMap.get("Goods_Unit_Price").toString());
				int totalPrice = Integer.parseInt(orderGoodsMap.get("Goods_Total_Price").toString());
				orderGoods.setOrdergoodsId(Integer.parseInt(orderGoodsMap.get("Ordergoods_ID").toString()));
				orderGoods.setGoodsCount(Integer.parseInt(orderGoodsMap.get("Goods_Count").toString())+goodsNumber);
				orderGoods.setGoodsTotalPrice(totalPrice+(price*goodsNumber));
				success = orderGoodsService.updateNumber(orderGoods);
			}else {
				searchMap.put("goodsId", goodsId);
				Map<String, Object> goodsMap = goodsInfoService.findGoodsInfoList(searchMap).get(0);
				orderGoods = new OrderGoods();
				int price = Integer.parseInt(goodsMap.get("price").toString());
				orderGoods.setGoodsId(Integer.parseInt(goodsId));
				orderGoods.setGoodsCount(goodsNumber);
				orderGoods.setGoodsName(goodsMap.get("goodsName").toString());
				orderGoods.setGoodsUnitPrice(price);
				orderGoods.setPicture1(goodsMap.get("Picture1").toString());
				orderGoods.setGoodsTotalPrice(price*goodsNumber);
				orderGoods.setPeruserId(Integer.parseInt(userId));
				orderGoods.setOprDate(getNowTime());
				success = orderGoodsService.addOrderGoods(orderGoods);
			}
			if (success >0) {
				resultMap.put("success", "1");
			}else {
				resultMap.put("success", "0");
			}
		}else {
			resultMap.put("success", "0");
		}
		return resultMap;
	}
	
	/**
	 * 立即购买商品
	 * 
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/imdBuyGoods")
	@ResponseBody
	private Map<String, Object> imdBuyGoods(HttpServletRequest request) throws ParseException{
		String goodsId = request.getParameter("goodsId");
		String userId = request.getParameter("userId"); 
		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (userId !=null) {
			searchMap.put("goodsId", goodsId);
			Map<String, Object> goodsMap = goodsInfoService.findGoodsInfoList(searchMap).get(0);
			if (goodsMap !=null) {
				resultMap.put("success", "1");
				resultMap.put("goodsMap", goodsMap);
			}else {
				resultMap.put("success", "0");
			}
			
		}else {
			resultMap.put("success", "0");
		}
		return resultMap;
	}
	
	/**
	 * 查询购物车商品数量
	 * 
	 * @param request
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/queryOrderGoodsCount")
	@ResponseBody
	private Map<String, Object> queryOrderGoodsCount(HttpServletRequest request) throws ParseException{
		String userId = request.getParameter("userId"); 
		int count = 0;
		Map<String, Object> searchMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (userId !=null) {
			searchMap.put("userId", userId);
			count = orderGoodsService.findOrderGoodsCount(searchMap);
			System.err.println(64646546);
			if (count>0) {
				resultMap.put("success", "1");
				resultMap.put("count", count);
			}else {
				resultMap.put("success", "0");
			}
			
		}else {
			resultMap.put("success", "0");
		}
		return resultMap;
	}
	
	
	/**
	 * 删除订单商品信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteOrderGoods.action")
	@ResponseBody
	private Map<String, Object> deleteOrderGoods(HttpServletRequest request){
		String orderGoodsId = request.getParameter("orderGoodsId");
		int success = 0;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (orderGoodsId !=null) {
			success = orderGoodsService.deleteOrderGoods(Integer.parseInt(orderGoodsId));
			if (success >0) {
				resultMap.put("success", "1");
			}else {
				resultMap.put("success", "0");
			}
		}else {
			resultMap.put("success", "0");
		}
		return resultMap;
	}
}
